/*
 * Copyright 2010 The MIauto Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
#include <avr/io.h>

#include "usart.h"

void USART_Init()
{
	UCSRB |= (1 << RXEN) | (1 << TXEN) | (1 << RXCIE); // Turn on the transmission and reception circuitry
	UCSRC |= (1 << URSEL) | (1 << UCSZ0) | (1 << UCSZ1); // Use 8-bit character sizes

	/* set baud rate */
	UBRRL = BAUD_PRESCALE; // Load lower 8-bits of the baud rate value into the low byte of the UBRR register
	UBRRH = (BAUD_PRESCALE >> 8); // Load upper 8-bits of the baud rate value into the high byte of the UBRR register
}

void USART_Transmit(uint8_t data)
{
	/* wait for empty transmit buffer */
	while (!(UCSRA & (1 << UDRE)))
		;

	/* put data into buffer, sends the data */
	UDR = data;
}

unsigned char USART_Receive(void)
{
	/* wait for data to be received */
	while (!(UCSRA & (1 << RXC)))
		;

	/* return received data from buffer */
	return UDR;
}

void USART_Flush(void)
{
	uint8_t dummy;
	while (UCSRA & (1 << RXC))
		dummy = UDR;
}
